<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="search-bar">
      <el-form-item label="备件编号" prop="partNo">
        <el-input
          v-model="queryParams.partNo"
          placeholder="请输入备件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入备件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备件仓库" prop="warehouseCode">
        <el-select
          v-model="queryParams.warehouseCode"
          placeholder="请选择备件仓库"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="w in warehouseOptions"
            :key="w.warehouseCode || w.code || w.value"
            :label="w.warehouseName || w.name || w.label"
            :value="w.warehouseCode || w.code || w.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格型号" prop="specNo">
        <el-input
          v-model="queryParams.specNo"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备件类型" prop="partTypeCode">
        <el-select
          v-model="queryParams.partTypeCode"
          placeholder="请选择备件类型"
          clearable
          @change="handleQuery"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="type in partTypeOptions"
            :key="type.code"
            :label="type.name"
            :value="type.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:part:add']"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:part:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partList" :fit="true" class="responsive-table">
      <el-table-column label="备件编号" align="center" prop="partNo" :min-width="180" show-overflow-tooltip resizable/>
      <el-table-column label="备件名称" align="center" prop="partName" :min-width="220" show-overflow-tooltip resizable/>
      <el-table-column label="规格型号" align="center" prop="specNo" :min-width="220" show-overflow-tooltip resizable/>
      <el-table-column label="备件类型" align="center" prop="partTypeCode" :min-width="120" resizable>
        <template slot-scope="scope">
          <span>{{ getPartTypeName(scope.row.partTypeCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件仓库" align="center" prop="warehouseCode" :min-width="140" show-overflow-tooltip resizable>
        <template slot-scope="scope">
          <span>{{ getWarehouseName(scope.row.warehouseCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存总数" align="center" prop="stockTotal" :min-width="120" show-overflow-tooltip resizable>
        <template slot-scope="scope">
          <span>{{ Math.floor(scope.row.stockTotal || 0) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :min-width="220" resizable>
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:part:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            style="color:#F56C6C"
            v-hasPermi="['system:part:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleStockDetail(scope.row)"
            v-hasPermi="['system:part:query']"
          >出入库明细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listPart, listPartDTO, getPart, delPart } from "@/api/inventory/part"
import TypeTag from '@/views/components/TypeTag.vue'
import RightToolbar from '@/components/RightToolbar'

export default {
  name: "Part",
  components: {
    TypeTag,
    RightToolbar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 备件表格数据
      partList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        partNo: null,
        partName: null,
        specNo: null,
        partTypeCode: null,
        warehouseCode: null,
        enabled: null
      },
      // 仓库下拉选项
      warehouseOptions: [],
      // 备件类型下拉选项
      partTypeOptions: []
    }
  },
  async created() {
    await Promise.all([
      this.loadWarehouses(),
      this.loadPartTypes()
    ])
    // 在字典加载完成后再取列表，避免编码到文字后跳
    await this.getList()
  },
  methods: {
    // 加载仓库列表
    loadWarehouses() {
      if (this.$apiWarehouseLoaded) return
      import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouse || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
            this.warehouseOptions = res.rows || res.data || []
            this.$apiWarehouseLoaded = true
          })
        }
      }).catch(() => {})
    },
    // 加载备件类型列表
    loadPartTypes() {
      if (this.$apiPartTypeLoaded) return
      import('@/api/dict/partType').then(mod => {
        const listFn = mod.listPartType || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999, enabled: 1 }).then(res => {
            this.partTypeOptions = res.rows || res.data || []
            this.$apiPartTypeLoaded = true
          })
        }
      }).catch(() => {})
    },
            /** 查询备件列表 */
            getList() {
              this.loading = true
              const params = {
                ...this.queryParams,
                name: this.queryParams.partName,
                orderByColumn: 'updatedAt',
                isAsc: 'false'
              }
              return listPartDTO(params).then(response => {
                const rows = response.data || []
                const typeMap = new Map((this.partTypeOptions||[]).map(t => [t.code, t.name]))
                const whMap = new Map((this.warehouseOptions||[]).map(w => [w.warehouseCode||w.code||w.value, w.warehouseName||w.name||w.label]))
                this.partList = rows.map(r => ({
                  ...r,
                  partTypeName: typeMap.get(r.partTypeCode) || r.partTypeCode,
                  warehouseName: whMap.get(r.warehouseCode) || r.warehouseCode
                }))
                this.total = rows.length
              }).finally(()=>{
                this.loading = false
              })
            },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 切换搜索显示 */
    toggleSearch() {
      this.showSearch = !this.showSearch
    },
    /** 新增按钮操作：路由跳转 */
    handleAdd() {
      this.$router.push({ path: '/system/part-add' })
    },
    /** 修改按钮操作：路由跳转 */
    handleUpdate(row) {
      const partNo = row.partNo || this.ids[0]
      if (!partNo) return
      this.$router.push({ path: `/system/part-edit/${partNo}` })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const partNos = row.partNo || this.ids
      this.$modal.confirm('是否确认删除备件编号为"' + partNos + '"的数据项？').then(function() {
        return delPart(partNos)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 出入库明细操作 */
    handleStockDetail(row) {
      this.$router.push({ path: '/system/item/index', query: { partNo: row.partNo } })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/part/export', {
        ...this.queryParams
      }, `part_${new Date().getTime()}.xlsx`)
    },
    /** 获取备件类型名称 */
    getPartTypeName(code) {
      if (!code) return '';
      const partType = this.partTypeOptions.find(type => type.code === code);
      return partType ? partType.name : code;
    },
    /** 获取仓库名称 */
    getWarehouseName(code) {
      if (!code) return '';
      const warehouse = this.warehouseOptions.find(w => (w.warehouseCode||w.code||w.value) === code);
      return warehouse ? (warehouse.warehouseName||warehouse.name||warehouse.label) : code;
    },
  }
}
</script>

<style scoped>
.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
}
.responsive-table .el-table__header-wrapper table,
.responsive-table .el-table__body-wrapper table {
  table-layout: fixed;
  width: 100%;
}
.responsive-table .el-table__body-wrapper { overflow-x: auto; }
.responsive-table .cell { white-space: nowrap; }
.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.search-buttons {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  align-items: center;
}

/* 统一按钮样式 */
.operation-buttons .el-button {
  border-radius: 4px;
  font-weight: 500;
}

.operation-buttons .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.operation-buttons .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.operation-buttons .el-button--text {
  color: #409EFF;
  padding: 8px 12px;
}

.operation-buttons .el-button--text:hover {
  color: #66b1ff;
}
</style>
